package com.lipi.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lipi.common.utils.PageUtils;
import com.lipi.common.utils.Query;
import com.lipi.mall.product.dao.BrandDao;
import com.lipi.mall.product.entity.BrandEntity;
import com.lipi.mall.product.service.BrandService;
import com.lipi.mall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //模糊查询 入参 String key;
        String key = (String) params.get("key");
        QueryWrapper<BrandEntity> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(key)) {
            wrapper.eq("brand_id", key).or().like("name", key);
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void updateDetail(BrandEntity brand) {
        this.updateById(brand);
        //更新冗余name的数据
        if (StringUtils.isNotEmpty(brand.getName())) {
            //更新分类-品牌关联表的冗余信息
            categoryBrandRelationService.updateBrand(brand.getBrandId(), brand.getName());
        }


    }

    @Override
    public List<BrandEntity> getBrandByIds(List<Long> brandIds) {
        if (!CollectionUtils.isEmpty(brandIds)) {
            List<BrandEntity> collect = brandIds.stream().map(
                    brandId -> {
                        return getBrandById(brandId);
                    }
            ).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    @Cacheable(value = "brand", key = "'brandInfo'+#root.args[0]")
    public BrandEntity getBrandById(Long brandId) {
        if (brandId != null) {
            return this.baseMapper.selectById(brandId);
        }
        return null;
    }
}